package Test;

public class 环形链表 {
    /********************第一种*************************/
    /****判断有环无环
     *
     */
    public boolean hasCycle(ListNode head) {
        ListNode slow,fast;
        slow=fast=head;
        while (fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            if(fast==slow) return true;

        }
        return false;
    }
    /********************第二种*************************/
    /**
     * 返回入环节点
     */
    public ListNode detectCycle(ListNode head) {
        ListNode slow,fast;
        slow=fast=head;
        while (fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            if(fast==slow) break;

        }
        if(fast==null||fast.next==null){
            return null;
        }
        slow=head;
        while (slow!=fast){
            slow=slow.next;
            fast=fast.next;
        }
        return slow;
    }
}
